<?php

namespace App\Handles;

use GuzzleHttp\Client;
use Overtrue\Pinyin\Pinyin;

class SlugTranslateHandler
{
    public function translate($text)
    {
        //实例化HTTP客户端
        $http = new Client(['timeout'=>2.0]);

        //初始化配置信息
        $api = config('services.baidu_translate.url');
        $app_id = config('services.baidu_translate.app_id');
        $key = config('services.baidu_translate.key');
        $salt = time();

        // 如果没有配置百度翻译，自动使用兼容的拼音方案
        if (empty($app_id) || empty($key)) {
            return $this->pinyin($text);
        }

        $sign = md5($app_id.$text.$salt.$key);

        //构建请求参数
        /*$query = http_build_query([
            'q' => $text,
            'from' => 'zh',
            'to' => 'en',
            'appid' => $app_id,
            'salt' => $salt,
            'sign' => $sign
        ]);*/

        //发送http get请求
        $response = $http->post($api,[
            "form_params" => [
                'q' => $text,
                'from' => 'zh',
                'to' => 'en',
                'appid' => $app_id,
                'salt' => $salt,
                'sign' => $sign
            ]
        ]);
        $result = json_decode($response->getBody(),true);
        //尝试获取翻译结果
        if (isset($result['trans_result'][0]['dst'])) {
            return str_slug($result['trans_result'][0]['dst']);
        }

        return $this->pinyin($text);
    }

    public function pinyin($text)
    {
        return str_slug(app(Pinyin::class)->permalink($text));
    }
}